package com.dgt.trade.controller;

import com.dgt.trade.entitys.yifu.Subaccounts;
import com.dgt.trade.utils.*;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.dgt.trade.entitys.User;
import com.dgt.trade.service.IUserService;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Controller
public class RegisterController extends BaseController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/register")
    @ResponseBody
    public Data login(String mobile, String password) {
        Integer status = null;
        String message = null;
        String SubAccountID = null;
        String SubLink = null;
        String Password = null;
        Data data = new Data();
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(password)) {
            data.setCode(4001);
            data.setMsg("手机号或密码不能为空");
            return data;
        }
        boolean bool = checkBindMobile(mobile);
        if (!bool) {
            data.setCode(4002);
            data.setMsg("手机号已被注册");
            return data;
        }

        //逸富注册
        String time = String.valueOf(new Date().getTime());
        Map<String, String> map = new LinkedHashMap<String, String>();
        Subaccounts subaccounts = new Subaccounts();
        subaccounts.setOrgID("lxw");
        subaccounts.setAgentID("test");
        subaccounts.setPhone(mobile);
        subaccounts.setSubAccountName("a" + mobile);
        subaccounts.setPassword(password);
        subaccounts.setParentAccountID("8888061");
        subaccounts.setSystemID("1");
        subaccounts.setAccountType("1");
        subaccounts.setMarginTemplateID("110");
        subaccounts.setCommissionTemplateID("74");
        subaccounts.setRiskTemplateID("68");
        subaccounts.setMonitorID("test");
        subaccounts.setTimeStamp(time);
        subaccounts.setVersion("1.0");
        String str = MD5Util.MD5(subaccounts.getOrgID(), subaccounts.getAgentID(), subaccounts.getPhone(), subaccounts.getSubAccountName(), subaccounts.getPassword(), subaccounts.getParentAccountID(), subaccounts.getSystemID(), subaccounts.getAccountType(), subaccounts.getMarginTemplateID(), subaccounts.getCommissionTemplateID(), subaccounts.getRiskTemplateID(), subaccounts.getMonitorID(), subaccounts.getTimeStamp(), subaccounts.getVersion());
        subaccounts.setSignMsg(str);

        map.put("OrgID", subaccounts.getOrgID());
        map.put("AgentID", subaccounts.getAgentID());
        map.put("Phone", subaccounts.getPhone());
        map.put("SubAccountName", subaccounts.getSubAccountName());
        map.put("Password", subaccounts.getPassword());
        map.put("ParentAccountID", subaccounts.getParentAccountID());
        map.put("SystemID", subaccounts.getSystemID());
        map.put("AccountType", subaccounts.getAccountType());
        map.put("MarginTemplateID", subaccounts.getMarginTemplateID());
        map.put("CommissionTemplateID", subaccounts.getCommissionTemplateID());
        map.put("RiskTemplateID", subaccounts.getRiskTemplateID());
        map.put("MonitorID", subaccounts.getMonitorID());
        map.put("TimeStamp", subaccounts.getTimeStamp());
        map.put("Version", subaccounts.getVersion());
        map.put("SignMsg", subaccounts.getSignMsg());
        String query = MapToStringSplicing.createLinkStringByGet(map);
        try {

            String result =  HttpClientUtil.putProcessRuntimeTask("http://120.55.162.84:8050/api/subaccounts?"+query,map);
            JsonParser parser = new JsonParser();
            JsonObject object = (JsonObject) parser.parse(result);
            JsonArray array = null;
            JsonObject subObject = null;
            status = object.get("status").getAsInt();
            if (status == 0) {
                array = object.get("data").getAsJsonArray();
                for (int i = 0; i < array.size(); i++) {
                    subObject = array.get(i).getAsJsonObject();
                    SubAccountID = subObject.get("SubAccountID").getAsString();
                    SubLink = subObject.get("SubLink").getAsString();
                    Password = subObject.get("Password").getAsString();
                }
            } else {
                message = object.get("message").getAsString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (status != 0 && message != null) {
            data.setCode(status);
            data.setMsg(message);
        } else {
            userService.registerUser(mobile, password,SubAccountID);
            User user = userService.getMemberByMobile(mobile);
            user.setPassword(null);
            request.getSession().setAttribute(ConstantsUtils.LOGIN_KEY_FLAG, JSON.toJSONString(user));
            data.setCode(200);
        }
        return data;
    }

    @RequestMapping("/checkMobile")
    @ResponseBody
    public Data checkMobile(String mobile) {
        Data data = new Data();
        if (StringUtils.isBlank(mobile)) {
            data.setCode(4001);
            data.setMsg("手机号不能为空");
            return data;
        }
        boolean bool = checkBindMobile(mobile);
        if (!bool) {
            data.setCode(4002);
            data.setMsg("手机号已被注册");
            return data;
        }
        data.setCode(200);
        data.setObj(bool);
        return data;
    }

    @RequestMapping("/sendMobileMsg")
    @ResponseBody
    public Data sendMobileMsg(String mobile) {
        Data data = new Data();
        if (StringUtils.isBlank(mobile)) {
            data.setCode(4001);
            data.setMsg("手机号不能为空");
            return data;
        }
        boolean bool = checkBindMobile(mobile);
        if (!bool) {
            data.setCode(4002);
            data.setMsg("手机号已被注册");
            return data;
        }
        String validateCode = CodeUtils.getNumber4FromRandom();  // 生成验证码
        request.getSession().setAttribute(ConstantsUtils.MSG_KEY_FLAG + mobile, validateCode);
        /****/
        //发送短信
        ShortMessageUtil.getRequest2(mobile, validateCode);
        /****/
        data.setCode(200);
        data.setMsg("发送成功");
        return data;
    }

    @RequestMapping("/checkMobileMsg")
    @ResponseBody
    public Data checkMobileMsg(String mobile, String msgCode) {
        Data data = new Data();
        if (StringUtils.isBlank(msgCode)) {
            data.setCode(4001);
            data.setMsg("验证码不能为空");
            return data;
        }
        String code = (String) request.getSession().getAttribute(ConstantsUtils.MSG_KEY_FLAG + mobile);
        if (!msgCode.equals(code)) {
            data.setCode(4002);
            data.setMsg("验证码不正确");
            return data;
        }
        data.setCode(200);
        data.setMsg("验证码成功");
        return data;
    }


    private boolean checkBindMobile(String mobile) {
        boolean bool = userService.chekMobile(mobile);
        return bool;
    }


}
